package com.xueliman.iov.auth_server_resource_common.other;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author zxg
 * 对带有@RestController的接口返回的值，进行增强处理，类似AOP思想
 */

@RestControllerAdvice(basePackages = "com.xueliman.iov")
@Slf4j
public class BaseResponseAdvice implements ResponseBodyAdvice<Object> {
    public static final String T_REQUEST_ID = "zxg";

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object object, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {

        //Feign请求时通过拦截器设置请求头，如果是Feign请求则直接返回实体对象
        boolean isFeign = serverHttpRequest.getHeaders().containsKey(T_REQUEST_ID);

        if(isFeign){
            return object;
        }

        if(object instanceof String){
            return objectMapper.writeValueAsString(SingleResultBundle.success(object));
        }

        if(object instanceof SingleResultBundle){
            return object;
        }

        return SingleResultBundle.success(object);
    }

}
